<?php

namespace app\index\controller;

use app\admin\controller\Order;
use app\common\entity\Config;
use app\common\entity\Goods;
use app\common\entity\GoodsOrders;
use app\common\entity\MywalletLog;
use app\common\entity\Orders;
use app\common\entity\Proportion;
use app\common\entity\ShopUserAddress;
use app\index\model\SendCode;
use think\Db;
use think\Request;
use app\common\entity\User;
use think\captcha\Captcha;
use app\common\entity\Message;
use app\common\entity\Image;
use app\common\entity\Article;
use app\common\entity\GoodsCategory;



class Shop extends Base
{

    public function index()
    {

        $img = Image::where('types', 1)->order('sort desc,id desc')->select();
        $notice = Article::where('category', 1)->where('status',1)->order('sort desc,article_id desc')->find();
        $category = GoodsCategory::order('sort asc')->select();
        $goods = Goods::where('status',1)->order('sort asc,addtime desc')->select();
        foreach($goods as $k=>$v){
            $goods[$k]['goods_pic'] = json_decode($v['goods_pic'],true)[0];
            $goods[$k]['gyg'] = \app\common\entity\Mywallet::cnyToGyg($v['goods_prices']);
        }
        $info = ['banner'=>$img,'notice'=>$notice,'category'=>$category,'goods'=>$goods];
        return json(['code' => 0, 'message' => '请求成功', 'info' => $info]);
    }




    public function goods_list(Request $request){
        if ($request->isPost()) {

            $page = $request->post('page',1);
            $limit = $request->post('limit',10);
            $category = $request->post('category_id');
            if(!$category){
                $category = Db::table('goods_category')->value('category_id');
            }

            $keyword = htmlspecialchars(trim($request->post('keyword')));
            $goodsModel = new \app\common\entity\Goods();
            if (!empty($keyword) && !empty($category)) {

                $goodsLists = $goodsModel->hckGoodsLists($category, $keyword, $page, $limit);
            } elseif (!empty($category) && empty($keyword)) {


                $goodsLists = $goodsModel->hcGoodsLists($category, $page, $limit);
            } elseif (!empty($keyword) && empty($category)) {

                $goodsLists = $goodsModel->hkGoodsLists($keyword, $page, $limit);

            } else {

                $goodsLists = $goodsModel->getGoodsLists($page, $limit);

            }

            //商品列表
            if ($goodsLists) {
                foreach ($goodsLists as $k => &$v) {

                    $img = json_decode($v['goods_pic']);
                    $goodsLists[$k]['goods_pic'] = $img[0];
                    $v['goods_prices'] = round($v['goods_prices'] , 2);
                    $goodsLists[$k]['gyg'] = \app\common\entity\Mywallet::cnyToGyg($v['goods_prices']);
                }
                return json(['code' => 0, 'message' => '获取成功', 'info' => $goodsLists]);
            }
            return json(['code' => 1, 'message' => '获取失败']);
        }
    }




    public function detail(Request $request)
    {
        $goodsId = $request->post('id');
        $goodsModel = new \app\common\entity\Goods();
        $goodsDetail = $goodsModel->getGoodsDetail($goodsId);
        if(!$goodsDetail){
            return json(['code' => 1, 'message' => '没有商品信息']);
        }
//        $goodsDetail['goods_content'] = (new \app\common\entity\Article())->updImgUrl($goodsDetail['goods_content']);

        $goodsDetail['goods_pic'] = json_decode($goodsDetail['goods_pic']);
        $goodsDetail['goods_img'] = $goodsDetail['goods_pic'][0];
        $goodsDetail['goods_content'] = htmlspecialchars_decode($goodsDetail['goods_content']);
        $goodsDetail['sell'] = Orders::where('goods_id',$goodsDetail['id'])->sum('pay_num');

        $goodsDetail['gyg'] = \app\common\entity\Mywallet::cnyToGyg($goodsDetail['goods_prices']);
        //轮播图
        // $goodsImgs = $goodsModel->getGoodsPic($goodsDetail['id']);
        $goodsImgs = [];

        array_unshift($goodsImgs, $goodsDetail['goods_pic']);
        if ($goodsDetail) {
            $pp = [];
            $ppv = [];
            $pps = [];
            if($goodsDetail['is_pp']){


                $ppk = Db::name('GoodsPpk')->where('gid', $goodsDetail['id'])->order('sort,id')->select();
                if (!empty($ppk)) {
                    $rs = Db::name('GoodsPpv')->where('gid', $goodsDetail['id'])->whereIn('gkid', array_column($ppk, 'id'))->order('sort,id')->select();
                    foreach ($rs as $v) {
                        $ppv[$v['gkid']][] = [
                            'id' => $v['id'],
                            'ppv' => $v['ppv']
                        ];
                    }
                }
                foreach ($ppk as $v) {
                    $pp[] = [
                        'id' => $v['id'],
                        'ppk' => $v['ppk'],
                        'ppv' => empty($ppv[$v['id']]) ? [] : $ppv[$v['id']],
                    ];

                }

                $pps = Db::name('GoodsPps')->where('gid', $goodsDetail['id'])->column('key,stock');

            }
            $goodsDetail['pp'] = $pp;
            $goodsDetail['pps'] = $pps;
            //return json(['code' => 0, 'message' => '获取成功', 'info' => $goodsDetail, 'img' => $goodsDetail['goods_pic'], 'address' => $address]);
            if($ppvs = $request->post('select')){
                $goodsDetail['ppvs'] = $this->getPPVS($ppvs);
            }
            return json(['code' => 0, 'message' => '获取成功', 'info' => $goodsDetail]);
        }
        return json(['code' => 1, 'message' => '获取失败']);

    }

    private function getPPVS($ppvs){

        $list = Db::name('goods_ppv')->alias('v')
            ->join('goods_ppk k','v.gkid = k.id')
            ->field('v.ppv,k.ppk')
            ->whereIn('v.id',$ppvs)
            ->select();
        $arr = [];
        foreach ($list as $k=>$v){
            $arr[] = $v['ppk'].':'.$v['ppv'];
        }
        return implode(',',$arr);
    }



    public function getCategory(){
        $category = Db::table('goods_category')->select();
        return json(['code' => 0, 'message' => '获取成功', 'info' => $category]);
    }






    public function toOrder(Request $request){

        if($request->post('type') == 1){
            $goodsId = $request->post('goods_id');
            $num = $request->post('num');
            $key = $request->post('key');
            $goodsModel = new \app\common\entity\Goods();
            $goodsDetail = $goodsModel->getGoodsDetail($goodsId);
            if(!$goodsDetail){
                return json(['code' => 1, 'message' => '没有商品信息']);
            }
            $goodsDetail['goods_pic'] = json_decode($goodsDetail['goods_pic']);
            $item = [
                'id'=>$goodsId,
                'goods_title'=>$goodsDetail['goods_title'],
                'goods_describe'=>$goodsDetail['goods_describe'],
                'goods_prices'=>$goodsDetail['goods_prices'],
                'goods_img'=>$goodsDetail['goods_pic'][0],
                'num'=>$num,
                'pay_num'=>$num,
                'goods_old'=>$goodsDetail['goods_old'],
                'key'=>$key,
            ];
            if($goodsDetail['is_pp']){
                $item['ppvs'] = $this->getPPVS($key);
            }


            $address = ShopUserAddress::where('uid', $this->userId)->order('status desc')->find();

            return json(['code' => 0, 'message' => '获取成功', 'info' => [$item], 'address' => $address]);
        }else{
            $carId = $request->post('car_id');
            $shopcar = Db::name('shopcar')->whereIn('id',$carId)->select();//print_r($shopcar);die;
            $info = $this->details($shopcar);
            $address = ShopUserAddress::where('uid', $this->userId)->order('status desc')->find();
            return json(['code' => 0, 'message' => '获取成功', 'info' => $info, 'address' => $address]);
        }
        return json(['code' => 1, 'message' => '获取失败']);
    }

    private function details($shopcar){
        $goodsModel = new \app\common\entity\Goods();
        $arr = [];
        foreach($shopcar as $k=>$v){
            $goods = $goodsModel->getGoodsDetail($v['goods_id']);
            $goods['goods_pic'] = json_decode($goods['goods_pic']);
            $item = [
                'id'=>$goods['id'],
                'goods_title'=>$goods['goods_title'],
                'goods_describe'=>$goods['goods_describe'],
                'goods_prices'=>$goods['goods_prices'],
                'goods_img'=>$goods['goods_pic'][0],
                'num'=>$v['num'],
                'goods_old'=>$goods['goods_old'],
                'key'=>$v['key'],
                'pp'=>$v['pp'],
                'car_id'=>$v['id'],
                'select'=>false,
            ];
            if($goods['is_pp']){
                $item['ppvs'] = $this->getPPVS(implode(',',explode('_',$v['pp'])));
            }

            $arr[] = $item;
        }
        return $arr;
    }

    public function insertOrder(Request $request)
    {
        $uid = $this->userId;
        $user_info = User::where('id', $this->userId)->find();
        if ($user_info['status'] == -1) {
            return json(['code' => 1, 'message' => '用户已被封禁']);
        }

        //检测地址
        $address_id = $request->post('address');
        if (!$address_id) {
            return json(['code' => 1, 'message' => '地址信息未填写全']);
        }
        $addressInfo = ShopUserAddress::where('id', $address_id)->find();


        //商品
        $orderInfo = $request->post('info/a');
        if (!$orderInfo) {
            return json(['code' => 1, 'message' => '请求信息错误']);
        }
        $oldOrder = Orders::where('create_time', '>', strtotime(date('Y-m-d')))->count();
        $orderNumber = $this->setOrderNumber($uid, $oldOrder + 1);
        $goodsInfo = [];
        $total_money_cansell = 0;
        $order_name = '金运来';
        foreach ($orderInfo as $k => $v) {

            $item = Goods::where('id', $v['id'])->find();

            if (!$item) {
                return json(['code' => 1, 'message' => '商品不存在']);
            }
            if ($order_name == '金运来') {
                $order_name = $item['goods_title'];
            }
            if ($item['goods_num'] - $v['num'] < 0) {
                return json(['code' => 1, 'message' => '库存不足']);
            }
            $PPandKey = $this->getPPandKey($v['key']);
            $pay_money = bcmul($item['goods_prices'], $v['num'], 2);
            $total_money_cansell = bcadd($total_money_cansell, $pay_money, 2);
            $goodsInfo[] = [
                'order_number' => $orderNumber,
                'user_id' => $uid,
                'number' => $v['num'],
                'user_name' => $addressInfo['real_name'],
                'mobile' => $addressInfo['mobile'],
                'address' => $addressInfo['city_address'] . $addressInfo['address'],
                'price' => $item['goods_prices'],
                // 'pay_time' => time(),
                'status' => 0,
                'create_time' => time(),
                'goods_id' => $v['id'],
                'pay_num' => $v['num'],
                'pay_money' => $pay_money,
                'pp' => $PPandKey['pp'],
                'key' => $PPandKey['key'],
            ];

            if (isset($v['car_id'])) {
                Db::name('shopcar')->where('id', $v['car_id'])->delete();
            }
        }
        $orderModel = new Orders();
        $insert = $orderModel->insertAll($goodsInfo);
        if($insert){
           //$this->pay($orderNumber);
            return json(['code' => 0, 'info' =>['orderNumber'=>$orderNumber,'amount'=>$total_money_cansell*1,'title'=>$order_name] ]);

        }else{
            return json(['code' => 1, 'message' => '预付款失败']);
        }


    }


    public function pay($order_number){
        #@todo 签名
        //$order_number = $request->post('order_number');
        $orderInfo = Orders::where('order_number',$order_number)->find();
        if ($orderInfo['status'] != 0) {
            return json(['code' => 1, 'message' => '订单状态错误']);
        }

        $update = Orders::where('order_number',$order_number)->update(['status'=>1,'pay_time'=>time()]);
        $orders =  Orders::where('order_number',$order_number)->select();
        $pps_stock = [];$order_stock = [];

        foreach($orders as $k=>$v){
            $goods = Goods::where('id',$v['goods_id'])->find();

            $order_stock[] = [
                'id'=>$v['goods_id'],
                'goods_num'=>$goods['goods_num'] - $v['pay_num'],
            ];
            if($v['key']){
                $pps = Db::name('goods_pps')->where(['gid'=>$v['goods_id'],'key'=>$v['key']])->find();

                $pps_stock[] = [
                    'gid'=>$v['goods_id'],
                    'key'=>$v['key'],
                    'stock'=>$pps['stock'] - $v['pay_num']
                ];
               /* if($pps['stock'] - $v['pay_num'] < 0){

                    print_r([$pps , $v['pay_num'],$v['goods_id']]);
                    return json(['code' => 1, 'message' => '库存不足']);
                }*/
            }
            #@todo 送gyg
            $gyg = \app\common\entity\Mywallet::cnyToGyg($goods['gyg']);
            MywalletLog::addLog($v['user_id'], $gyg, 2, '购买商品赠送', 1, 1);
            foreach($order_stock as $k=>$v){
                Goods::where('id',$v['id'])->update(['goods_num'=>$v['goods_num']]);
            }
            foreach($pps_stock as $k=>$v){
                Db::name('goods_pps')->where(['gid'=>$v['gid'],'key'=>$v['key']])->update(['stock'=>$v['stock']]);
            }


        }

        User::upLevel($this->userId);
//        echo "OK";

    }



    private function getPPandKey($ppvs){
        $list = Db::name('goods_ppv')
            ->field('id,ppv')
            ->whereIn('id',implode(',',explode('_',$ppvs)))
            ->select();
        $pp = [];
        $key = [];
        if($list) {
            foreach ($list as $k => $v) {
                $key[] = $v['id'];
                $pp[] = $v['ppv'];
            }
        }
        return ['pp'=>implode(',',$pp),'key'=>implode(',',$key)];
    }

    private function setOrderNumber($memberId,$num)
    {
        return date('Ymd') . $memberId . date('His') .$num;
    }

    #订单列表
    public function orderList(Request $request)
    {
        if ($request->isPost()) {

            $uid = $this->userId;
            $status = $request->post('status','all');

            $limit = $request->post('limit',10);
            $where = ['user_id'=> $uid];
            if ($status != 'all') {
                $where['status'] = $status;
            }else{
                $where['status'] = ['in','1,2,3'];
            }
            if($request->post('order_number')){
                $orderNumList = Db::name('orders')->where($where)->where('order_number','like','%'.$request->post('order_number').'%')->field('order_number')->order('create_time desc')->paginate($limit);
            }else{
                $orderNumList = Db::name('orders')->where($where)->field('order_number')->order('create_time desc')->paginate($limit);
            }
           // print_r(Db::name('orders')->getLastSql());die;
            $orderList = Orders::where($where)->order('pay_time desc')->select();

            foreach ($orderList as $k => &$v) {
                $goodsInfo = Goods::where('id', $v['goods_id'])->find();
                $img = json_decode($goodsInfo['goods_pic']);
                $v['goods_title'] = $goodsInfo['goods_title'];
                $v['img'] = $img[0];

                $v['pay_time'] = date("Y-m-d H:i:s", $v['pay_time']);
            }
            foreach($orderNumList as $k=>$v){
                $item = [
                    'orderNum'=>$v['order_number'],
                    'goods'=>[],
                    'countMoney'=>[],
                    'countGoods'=>0,
                ];
                $item['goods'] = [];
                $item['countMoney'] = 0;
                foreach($orderList as $key=>$val){
                    if($v['order_number'] == $val['order_number']){
                        $item['goods'][] = $val;
                        $item['countMoney'] = bcadd($item['countMoney'],$val['pay_money'],2);
                        $item['countGoods'] += $val['pay_num'];
                    }
                }

                $orderNumList[$k] = $item;
            }
            return json(['code' => 0, 'message' => '获取成功', 'info' => $orderNumList]);

        }
        return $this->fetch("orderlist", ['status' => $request->get('status')]);

    }

    public function delOrder(Request $request){
        $order_number = $request->post('order_number');
        if(!$order_number){
            return json(['code' => 1, 'message' => '操作失败']);
        }
        $del = Orders::where('order_number',$order_number)->update(['status'=>4]);
        if($del){
            return json(['code' => 0, 'message' => '操作成功']);
        }else{
            return json(['code' => 1, 'message' => '操作失败']);
        }
    }
    #确认收货
    public function chilkOrder(Request $request)
    {
        $order_number = $request->post('order_number');
        $res = Db::table('orders')->where('order_number', $order_number)->find();
        if ($res['status'] !== 2) {
            return json(['code' => 1, 'message' => '操作失败']);

        }
        $upd = Db::table('orders')->where('order_number', $order_number)->update(['status' => 3, 'finish_time' => time()]);
        if ($upd) {
            $orders = Db::table('orders')->where('order_number', $order_number)->select();
            foreach ($orders as $k=>$v){
                $goods = Goods::where('id',$v['goods_id'])->find();
                $gyg =  bcmul(\app\common\entity\Mywallet::cnyToGyg($goods['goods_prices']),$v['pay_num'],2);
                MywalletLog:: lockToGyg($this->userId,bcmul($gyg,bcmul(Config::getValue('gyg_order'),0.01,4),4),'确定收货释放',2);
                MywalletLog::activity($this->userId,$gyg);
            }

            return json(['code' => 0, 'message' => '操作成功']);
        }
        return json(['code' => 1, 'message' => '操作失败']);

    }


    #订单详情
    public function orderdetail(Request $request)
    {
        $order_number = $request->post('order_number');
        $orderInfo = Orders::where('order_number', $order_number)->select();
        if (!$orderInfo) {
            return json(['code' => 1, 'message' => '订单不存在']);

        }

        // var_dump($orderInfo);die;

        $order_name = '金运来';
        $total_money_cansell = 0;
        foreach($orderInfo as $k=>$v){

            $goodsInfo = Orders::table('goods')->where('id', $v['goods_id'])->find();
            if ($order_name == '金运来') {
                $order_name = $goodsInfo['goods_title'];
            }
            $img = json_decode($goodsInfo['goods_pic']);
            $orderInfo[$k]['goods_title'] = $goodsInfo['goods_title'];
            $orderInfo[$k]['img'] = $img[0];
            $orderInfo[$k]['oneprice'] = $goodsInfo['goods_prices'];
            $orderInfo[$k]['pay_time'] = date("Y-m-d H:i:s", $v['pay_time']);
            $total_money_cansell = bcadd($total_money_cansell, $v['pay_money'], 2);
           /* switch ($orderInfo[$k]['status']) {
                case 0:
                    $orderInfo[$k]['status'] = '待付款';
                    break;
                case 1:
                    $orderInfo[$k]['status'] = '待发货';
                    break;
                case 2:
                    $orderInfo[$k]['status'] = '待收货';
                    break;
                case 3:
                    $orderInfo[$k]['status'] = '已收货';
                    break;
                case 4:
                    $orderInfo[$k]['status'] = '交易失败';
                    break;
            }*/

            if ($orderInfo[$k]['status'] != 1) {
                $orderInfo[$k]['send_time'] = date("Y-m-d H:i:s", $v['send_time']);

            } else {
                $orderInfo[$k]['send_time'] = '等待发货中';

            }
        }


        if ($orderInfo) {

            return json(['code' => 0, 'message' => '获取成功', 'info' => ['order_number'=>$order_number,'orders'=>$orderInfo,'amount'=>$total_money_cansell*1,'title'=>$order_name]]);
        }
        return json(['code' => 1, 'message' => '获取失败']);

    }


    #加入购物车
    public function addShopCar(Request $request)
    {
        $uid = $this->userId;
        $goods_id = $request->post('goods_id');
        $num = $request->post('num',1);
        $find = Db::table('shopcar')->where('uid', $uid)->where('goods_id', $goods_id)->find();
        if ($find) {
            $upd = Db::table('shopcar')->where('uid', $uid)->where('goods_id', $goods_id)->update(['num' => $find['num'] + $num]);
            if ($upd) {
                return json(['code' => 0, 'message' => '添加成功']);
            }
            // dump($upd);die;
            return json(['code' => 1, 'message' => '添加失败']);

        }
        $log = [
            'uid' => $uid,
            'goods_id' => $goods_id,
            'num' => $num,
            'create_time' => time(),
        ];
        $key = $request->post('key');
        if (!empty($key)) {
            $mPPS = Db::name('GoodsPps');
            $pps = $mPPS->where([
                'gid' => $goods_id,
                'key' => $key
            ])->find();

            $log['key'] = $pps['key'];

            $ppv = Db::name('GoodsPpv')
                ->where('gid',$goods_id)
                ->whereIn('id', explode('_', $key))
                ->column('id,ppv');

            $log['pp'] = implode(',', $ppv);

        }
        $res = Db::table('shopcar')->insert($log);
        if ($res) {
            return json(['code' => 0, 'message' => '添加成功']);

        }
        return json(['code' => 1, 'message' => '添加失败']);

    }

    #购物车列表
    public function shopCarList(Request $request)
    {
        if ($request->isPost()) {
            $uid = $this->userId;
            $limit = $request->post('limit',10);
            $shopcar = Db::table('shopcar')->where('uid', $uid)->paginate($limit);

            $list = $this->details($shopcar);
           /* foreach ($list as $k => &$v) {
                $goodsInfo = Db::table('goods')->where('id', $v['goods_id'])->find();
                $img = json_decode($goodsInfo['goods_pic']);
                $v['goods_title'] = $goodsInfo['goods_title'];
                $v['goods_prices'] = round($goodsInfo['goods_prices'] , 2);
                $v['img'] = $img[0];

            }*/
            if (empty($list)) {
                return json(['code' => 0, 'message' => '暂无数据']);

            }

            if ($list) {
                return json(['code' => 0, 'message' => '获取成功', 'info' => $list]);

            }
            return json(['code' => 1, 'message' => '获取失败']);
        }
        return $this->fetch("shopCarList");

    }

    #删除购物车
    public function delShopCar(Request $request)
    {

        $uid = $this->userId;
        $car_id = $request->post('id');
        // dump($car_id);die;DELETE FROM `shopcar` WHERE `id` IN (36) AND `uid` = 215775
        $caridarr = explode(",", $car_id);
        if (!$uid || !$car_id) return json(['code' => 1, 'msg' => '缺少参数']);
        $res = Db::table('shopcar')->where(['id' => $caridarr, 'uid' => $uid])->delete();

        if ($res) {
            return json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '删除失败']);
        }
    }

    #编辑购物车
    public function updShopCar(Request $request)
    {
        if ($request->isPost()) {
            print_R( $request->post());
            $uid = $this->userId;
            $car_id = $request->post('id');
            $num = $request->post('num');
            $log = [
                'num' => $num,
                'create_time' => time(),
            ];
            $res = Db::table('shopcar')->where('id', $car_id)->update($log);
            if ($res) {
                return json(['code' => 0, 'message' => '编辑成功']);

            }
            return json(['code' => 1, 'message' => '编辑失败']);
        }
        return $this->fetch("updShopCar");

    }

    /**
     * [user_address_list 收货地址]
     * @return [type] [description]
     */
    public function user_address_list(Request $request)
    {
        $page = $request->post('page') ?? 1;
        $limit = $request->post('limit') ?? 10;
        $uid = $this->userId;
        $goods = DB::table('shop_user_address')
            ->field('id,uid,real_name,address,mobile,status,city_address')
            ->where('uid', $uid)
            ->limit($limit)
            ->page($page)
            ->select();

        return json(['code' => 0, 'msg' => '请求成功', 'info' => $goods]);
    }

    public function user_address_detail(Request $request)
    {
        $address_id = $request->post('address_id');
        $uid = $this->userId;
        $goods = DB::table('shop_user_address')
            ->field('id,uid,real_name,address,mobile,status,city_address')
            ->where('id',$address_id)
            ->where('uid', $uid)
            ->find();

        return json(['code' => 0, 'msg' => '请求成功', 'info' => $goods]);
    }

    /**
     * [user_address_default 默认收货地址]
     * @return [type] [description]
     */
    public function user_address_default(Request $request)
    {
        $address_id = $request->post('address_id');
        $uid = $this->userId;

        $goods = DB::table('shop_user_address')
            ->where('id', $address_id)
            ->where('uid', $uid)
            ->update(['status' => 1]);
        if (!$goods) {
            return json(['code' => 1, 'msg' => '修改失败']);
        }
        $goods = DB::table('shop_user_address')
            ->where('id', '<>', $address_id)
            ->where('uid', $uid)
            ->update(['status' => 0]);
        return json(['code' => 0, 'msg' => '操作成功']);
    }

    /**添加地址
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\PDOException
     */
    public function addWalletAddress(Request $request)
    {
        $uid = $this->userId;

        $validate = $this->validate($request->post(), '\app\index\validate\ShopUserAddress');
        if ($validate !== true) {
            return json(['code' => 1, 'msg' => $validate]);
        }
        $model = new ShopUserAddress();
        $model->startTrans();
        $res = $model->add($model, $uid, $request->post());

        if ($res) {
            $model->commit();
            return json(['code' => 0, 'msg' => '添加成功']);
        }
        $model->rollback();
        return json(['code' => 1, 'msg' => '添加失败']);

    }

    /**编辑地址
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function editWalletAddress(Request $request)
    {
        $uid = $this->userId;
        if ($request->isGet()) {
            $model = new ShopUserAddress();
            $list = $model->where('id', $request->get('id'))->where('uid', $uid)->find();
            if ($list) {
                return json(['code' => 0, 'msg' => '获取成功', 'info' => $list]);
            }
            return json(['code' => 1, 'msg' => '暂无数据']);
        }

        if ($request->isPost()) {

            $validate = $this->validate($request->post(), '\app\index\validate\ShopUserAddress');
            if ($validate !== true) {
                return json(['code' => 1, 'msg' => $validate]);
            }
            if (!$request->post('id')) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }

            $model = new ShopUserAddress();
            $model->startTrans();

            $res = $model->upd($model, $uid, $request->post());
            if ($res) {
                $model->commit();
                return json(['code' => 0, 'msg' => '修改成功']);
            }
            $model->rollback();
            return json(['code' => 1, 'msg' => '修改失败']);

        }
    }

    public function delWalletAddress(Request $request)
    {
        $uid = $this->userId;
        $model = new ShopUserAddress();
        $is_has = $model->where('uid', $uid)->count();
        if ($is_has <= 1) {
            return json(['code' => 1, 'msg' => '不可删除唯一地址']);
        }
        $list = $model->where('id', $request->post('id'))->where('uid', $uid)->delete();
        $is_defelt = $model->where('uid', $uid)->where('status', 1)->find();
        if (!$is_defelt) {
            $updInfo = $model->where('uid', $uid)->find();
            $model->where('id', $updInfo['id'])->setField('status', 1);
        }
        if ($list) {
            return json(['code' => 0, 'msg' => '删除成功']);
        }
        return json(['code' => 1, 'msg' => '暂无数据']);
    }




    function delivery(Request $request){
        $m = Db::name('orders');
        $info = $m->where([
            'order_number'    => $request->post('order_number',0),
            'user_id'   => $this->userId
        ])->field('id,status,express,expressnumber,address')->find();

        if(empty($info)) return json(['code' => 1, 'msg' => '无效订单']);
        if($info['status']<2) return json(['code' => 1, 'msg' => '暂未发货']);

        //参数设置
        $key = 'fIjXScRX2886'; //客户授权key
        $customer = 'B0EE0968FD1DE0D9581E0FDBD1B188F4'; //查询公司编号
        $param = array (
            'com' => $info['express'],			//快递公司编码
            'num' => $info['expressnumber'],	//快递单号
            'phone' => '',				//手机号
            'from' => '',				//出发地城市
            'to' => '',					//目的地城市
            'resultv2' => '1'			//开启行政区域解析
        );

        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);

        $url = 'http://poll.kuaidi100.com/poll/query.do';	//实时查询请求地址

        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $rs = curl_exec($ch);
        curl_close($ch);

        $express = GoodsOrders::getOneCate($info['express']);
        $info['express'] = $express['name'];
        if(!(!empty($rs) && ($rs = json_decode($rs, true)) && $rs['message']=='ok'))
            return json(['code' => 0, 'msg' => '暂无物流信息','info'=>['list'=>[],'info'=>$info]]);

        return json(['code' => 0, 'msg' => '查询成功','info'=>['list'=>$rs['data'],'info'=>$info]]);
    }
    public function cnyToGyg($num){
        $getToday = Proportion::getToday();
        $usdt_cny = Config::getValue('usdt_cny');
        return bcdiv(bcdiv($num,$usdt_cny,4),$getToday);
    }

}
